import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Connection } from 'typeorm';
import { User } from '../user/entities/user.entity';
import axios from 'axios';
// 修正导入方式
const { Api: TLSSigAPIv2 } = require('tls-sig-api-v2');
import { ConfigService } from '@nestjs/config';

@Injectable()
export class TencentImService {
  private readonly SDKAppID: number;
  private readonly adminUserId: string;
  private readonly secretKey: string;
  // 修正类型声明，使用 typeof 关键字
  private readonly api: typeof TLSSigAPIv2;

  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    private readonly connection: Connection,
    private readonly configService: ConfigService,
  ) {
 
  }

  // 生成腾讯云IM的用户ID
  public getTencentUserId(userId: number): string {
    return `user_${userId}`;
  }

  // 从腾讯云IM的userID中提取用户ID
  public extractUserIdFromTencentUserId(tencentUserId: string): number | null {
    // 假设tencentUserId的格式为 "user_123"，其中123是用户ID
    const match = tencentUserId.match(/^user_(\d+)$/);
    if (match && match[1]) {
      return parseInt(match[1], 10);
    }
    return null;
  }

  // 检查管理员账号是否已导入
  private async checkAndImportAdminUser(): Promise<boolean> {
    try {
      // 生成管理员签名
      const adminSig = this.api.genUserSig(this.adminUserId, 86400);
      
      // 检查管理员账号是否存在
      const checkUrl = `https://console.tim.qq.com/v4/im_open_login_svc/account_check?sdkappid=${this.SDKAppID}&identifier=${this.adminUserId}&usersig=${adminSig}&random=${Math.floor(Math.random() * 1000000)}&contenttype=json`;
      
      const checkResponse = await axios.post(checkUrl, {
        CheckItem: [
          { UserID: this.adminUserId }
        ]
      });
      
      if (checkResponse.data.ErrorCode !== 0) {
        throw new Error(`检查管理员账号失败: ${checkResponse.data.ErrorInfo}`);
      }
      
      const adminExists = checkResponse.data.ResultItem[0].AccountStatus === 'Imported';
      
      if (!adminExists) {
        // 导入管理员账号
        const importUrl = `https://console.tim.qq.com/v4/im_open_login_svc/account_import?sdkappid=${this.SDKAppID}&identifier=${this.adminUserId}&usersig=${adminSig}&random=${Math.floor(Math.random() * 1000000)}&contenttype=json`;
        
        const importResponse = await axios.post(importUrl, {
          UserID: this.adminUserId,
          Nick: '管理员',
          FaceUrl: ''
        });
        
        if (importResponse.data.ErrorCode !== 0) {
          throw new Error(`导入管理员账号失败: ${importResponse.data.ErrorInfo}`);
        }
      }
      
      return true;
    } catch (error) {
      throw new Error(`检查或导入管理员账号失败: ${error.message}`);
    }
  }

  // 导入单个用户到腾讯云IM
  async importUserToTencentIM(userId: number): Promise<{ tencentUserId: string }> {
    // 确保管理员账号已导入
    await this.checkAndImportAdminUser();
    
    // 查询用户信息
    const user = await this.userRepository.findOne({ where: { id: userId } });
    if (!user) {
      throw new Error(`用户ID ${userId} 不存在`);
    }
    
    const tencentUserId = this.getTencentUserId(user.id);
    
    // 生成管理员签名
    const adminSig = this.api.genUserSig(this.adminUserId, 86400);
    
    // 导入用户到腾讯云IM
    const url = `https://console.tim.qq.com/v4/im_open_login_svc/account_import?sdkappid=${this.SDKAppID}&identifier=${this.adminUserId}&usersig=${adminSig}&random=${Math.floor(Math.random() * 1000000)}&contenttype=json`;
    
    const requestBody = {
      UserID: tencentUserId,
      Nick: user.nickname || `用户${user.id}`,
      FaceUrl: user.avatar || ''
    };
    
    try {
      const response = await axios.post(url, requestBody);
      
      if (response.data.ErrorCode !== 0) {
        throw new Error(`导入用户失败: ${response.data.ErrorInfo}`);
      }
      
      // 保存映射关系到数据库
      await this.saveUserMapping(user.id, tencentUserId);
      
      return { tencentUserId };
    } catch (error) {
      if (error.response) {
        throw new Error(`导入用户失败: ${error.response.data.ErrorInfo || error.message}`);
      }
      throw error;
    }
  }

  // 批量导入用户到腾讯云IM
  async importUsersToTencentIM(userIds: number[]): Promise<{
    successCount: number;
    failCount: number;
    results: Array<{
      userId: number;
      success: boolean;
      tencentUserId?: string;
      error?: string;
    }>;
  }> {
    // 确保管理员账号已导入
    await this.checkAndImportAdminUser();
    
    const results = [];
    let successCount = 0;
    let failCount = 0;
    
    for (const userId of userIds) {
      try {
        const result = await this.importUserToTencentIM(userId);
        results.push({
          userId,
          success: true,
          tencentUserId: result.tencentUserId
        });
        successCount++;
        
        // 添加延迟，避免请求过快
        await new Promise(resolve => setTimeout(resolve, 200));
      } catch (error) {
        results.push({
          userId,
          success: false,
          error: error.message
        });
        failCount++;
      }
    }
    
    return {
      successCount,
      failCount,
      results
    };
  }

  // 导入所有用户到腾讯云IM
  async importAllUsersToTencentIM(): Promise<{
    successCount: number;
    failCount: number;
    totalCount: number;
  }> {
    // 确保管理员账号已导入
    await this.checkAndImportAdminUser();
    
    // 获取所有活跃用户
    const users = await this.userRepository.find({ where: { status: 1 } });
    
    let successCount = 0;
    let failCount = 0;
    
    for (const user of users) {
      try {
        await this.importUserToTencentIM(user.id);
        successCount++;
        
        // 添加延迟，避免请求过快
        await new Promise(resolve => setTimeout(resolve, 200));
      } catch (error) {
        failCount++;
      }
    }
    
    return {
      successCount,
      failCount,
      totalCount: users.length
    };
  }

  // 保存用户映射关系
  private async saveUserMapping(userId: number, tencentUserId: string): Promise<void> {
    try {
      // 检查表是否存在
      const tableExists = await this.connection.query(`
        SELECT COUNT(*) as count 
        FROM information_schema.tables 
        WHERE table_schema = DATABASE() 
        AND table_name = 'user_message_mapping'
      `);
      
      if (parseInt(tableExists[0].count) === 0) {
        // 创建映射表
        await this.connection.query(`
          CREATE TABLE IF NOT EXISTS user_message_mapping (
            id INT AUTO_INCREMENT PRIMARY KEY,
            userId INT NOT NULL,
            tencentUserId VARCHAR(255) NOT NULL,
            createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            UNIQUE KEY idx_user_id (userId),
            UNIQUE KEY idx_tencent_user_id (tencentUserId)
          ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
        `);
      }
      
      // 检查映射是否已存在
      const existingMapping = await this.connection.query(`
        SELECT id FROM user_message_mapping WHERE userId = ?
      `, [userId]);
      
      if (existingMapping.length > 0) {
        // 更新现有映射
        await this.connection.query(`
          UPDATE user_message_mapping 
          SET tencentUserId = ?, updatedAt = NOW() 
          WHERE userId = ?
        `, [tencentUserId, userId]);
      } else {
        // 创建新映射
        await this.connection.query(`
          INSERT INTO user_message_mapping (userId, tencentUserId) 
          VALUES (?, ?)
        `, [userId, tencentUserId]);
      }
    } catch (error) {
      throw new Error(`保存用户映射关系失败: ${error.message}`);
    }
  }
}




